package com.chuji.crmcj.act;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.LoginInfo;
import com.chuji.crmcj.utils.DialogUtil;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

/**
 * Todo   SPUtils.saveString(UIUtils.getContext(), "UserID", "F248611C-CB39-4806-919E-71DCD085D208");
 */
public class LoginActivity extends Activity implements TextWatcher {
    /*账号*/
    private EditText et_accounts;
    /*密码*/
    private EditText et_password;
    /*是否勾选*/
    private boolean isChecked = true;
    private ToggleButton togglebutton;
    /*登录*/
    private Button btn_login;
    private ProgressDialog progressDialog;
    //private Builder builder;
    private Context context = LoginActivity.this;
    private LinearLayout LinearLayout1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_login);
        View left = findViewById(R.id.ll_left1);

        //初始化组件
        et_accounts = (EditText) findViewById(R.id.et_accounts);
        et_password = (EditText) findViewById(R.id.et_password);

        btn_login = (Button) findViewById(R.id.btn_login);
        togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
        LinearLayout1 = (LinearLayout) findViewById(R.id.LinearLayout1);
        //添加输入框监听
        et_accounts.addTextChangedListener(this);
        et_password.addTextChangedListener(this);

        LinearLayout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收起软键盘
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginInProcess();
            }
        });

//        ImageView imageView = (ImageView) findViewById(R.id.ivBack);
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("你真的要退出吗？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        android.os.Process.killProcess(android.os.Process.myPid());

                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
    }

    private void loginInProcess() {

        //dialog = ProgressDialog.show(context, null, "加载中,请稍等...", false);
        progressDialog = new ProgressDialog(context, R.style.theme_customer_progress_dialog);
        //progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("加载中,请稍等...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        //得到用户输入的账号
        final String accounts = et_accounts.getText().toString();
        //得到用户输入的密码
        final String password = et_password.getText().toString();
        //初始化Volley
        String strURL = String.format(UrlUtils.Login + "User=%s&Pwd=%s&frm=", accounts, password);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.v("CatalogClient", response);
                JSONObject obj = JSONObject.parseObject(response);
                if (obj.getString("success") == "true") {
                    //用户信息保存
//                            JSONObject user = obj.getJSONObject("User");
//                            System.out.println(user);
                    int roleType = -1;
                    LoginInfo loginInfo = JSON.parseObject(response, LoginInfo.class);

                    if (loginInfo.getRole() == null) {
                        DialogUtil.show(context, "此账号没有关联角色！");
                        progressDialog.hide();
                        return;
                    }

                    if (loginInfo.getRole().get(0).getRoleName().equals("销售顾问")) {
                        roleType = 1;
                    } else if (loginInfo.getRole().get(0).getRoleName().equals("经理")) {
                        roleType = 2;
                    } else if (loginInfo.getRole().get(0).getRoleName().equals("销售总经理")) {
                        roleType = 3;
                    } else {
                        DialogUtil.show(context, "此账号不能登录系统！");
                        progressDialog.hide();
                        return;
                    }
                    Log.v("========>", String.valueOf(roleType));
//                            SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
//                            SharedPreferences.Editor editor = sharedPreferences.edit();
//                            Log.v("UserID==>", loginInfo.getUser().getUserID());
//                            editor.putString("userID", loginInfo.getUser().getUserID());
//                            editor.putString("username", accounts);
//                            editor.putString("password", password);
//                            editor.commit();

                    if (togglebutton.isChecked() == false) {
                        //没选中
                        et_accounts.setText(null);
                        et_password.setText(null);
                        SPUtils.saveBoolean(UIUtils.getContext(), "rembermima", false);
                    } else {
                        SPUtils.saveBoolean(UIUtils.getContext(), "rembermima", true);
                    }

                    SPUtils.saveString(UIUtils.getContext(), "username", accounts);
                    SPUtils.saveString(UIUtils.getContext(), "password", password);

                    //根据角色跳转对应页面
                    if (roleType == 1 || roleType == 2 || roleType == 3) {
                        //保存用户信息
                        SPUtils.saveInt(UIUtils.getContext(), "RoleType", roleType);
//                        SPUtils.saveString(UIUtils.getContext(), "UserID", "F248611C-CB39-4806-919E-71DCD085D208");
//                        SPUtils.saveString(UIUtils.getContext(), "UserID", "1227FC37-8E05-43ED-BE86-0CE5A401FD6F");
                        SPUtils.saveString(UIUtils.getContext(), "UserID", loginInfo.getUser().getUserID());
                        SPUtils.saveString(UIUtils.getContext(), "CompanyID", loginInfo.getUser().getCompanyID());

                        progressDialog.hide();

                        startActivity();
                        finish();
                    }
                } else {
                    DialogUtil.show(context, "登录失败,账号或密码不正确！");
                    progressDialog.hide();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                DialogUtil.show(context, "系统错误,登录失败！", 3000);
                progressDialog.hide();
            }
        });
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    public void startActivity() {
        Intent intent = new Intent(UIUtils.getContext(), MainActivity.class);
        UIUtils.startActivity(intent);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
//        /**
//         * 设置按钮灰置效果
//         */
//        final String Accounts = et_accounts.getText().toString();
//        final String Password = et_password.getText().toString();
//        if (CommonUtil.isEmpty(Accounts)) {
//            Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
//        } else if (!CommonUtil.isEmpty(Accounts) && CommonUtil.isEmpty(Password)) {
//            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
//        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();

        String username = SPUtils.getString(UIUtils.getContext(), "username", "");
        String password = SPUtils.getString(UIUtils.getContext(), "password", "");
        boolean remarkmima = SPUtils.getBoolean(UIUtils.getContext(), "rembermima", false);

        int roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);

        if (remarkmima == false) {
            et_accounts.setText("");
            et_password.setText("");
        } else {
            et_accounts.setText(username);
            et_password.setText(password);
            et_accounts.setSelection(username.length());
            et_password.setSelection(password.length());
        }

        //保存了username 和password 以后 直接登陆
        boolean zhuxiao = SPUtils.getBoolean(UIUtils.getContext(), "zhuxiao", false);

        if (zhuxiao) {
            SPUtils.saveBoolean(UIUtils.getContext(), "zhuxiao", false);
            return;
        } else {
            if (!username.isEmpty() && !password.isEmpty()) {
                if (roleType == 1 || roleType == 2 || roleType == 3) {
                    togglebutton.setChecked(true);
                    startActivity();
                    finish();
                }
            }
        }
    }
}
